package callnumber.gtdev5.com.photoVault.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * Created by cheng
 * PackageName FakeCall_4
 * 2018/8/18 10:40
 */

@SuppressLint("AppCompatCustomView")
public class TimeTextView extends TextView {

    private onTimeFinshListener onTimeFinshListener;
    private int pos=-1;
    public TimeTextView(Context context) {
        super(context);
    }

    public TimeTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 在控件被销毁时移除消息
        handler.removeMessages(0);
    }
    long Time;
    private boolean run = true; // 是否启动了
    @SuppressLint("NewApi")
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (run) {
                        long mTime = Time;
                        if (mTime > 0) {
                            format.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                            TimeTextView.this.setText( format.format(Time));
                            Time = Time - 1000;
                            handler.sendEmptyMessageDelayed(0, 1000);
                            if (TimeTextView.this.getText().equals("00:00:00")){
                                   if (onTimeFinshListener!=null){
                                    onTimeFinshListener.timeFinish(pos);
                                }
                            }
                        }
                    } else {
                        TimeTextView.this.setText("时间已结束");
                    }
              break;
               default:
                break;
            }


        }
    };

    @SuppressLint("NewApi")
    public void setTimes(long mT) {
        // 标示已经启动

        long t2 = System.currentTimeMillis();
        Time = mT - t2;
        if (Time > 0) {
            handler.removeMessages(0);
            handler.sendEmptyMessage(0);
        } else {
            TimeTextView.this.setText("时间已结束");
        }
    }

    public void stop() {
        run = false;
    }

    public  void setOnTimeFinshListener(onTimeFinshListener listener){
        this.onTimeFinshListener=listener;
    }

    public void setPos(int position){
        this.pos=position;
    }
    public interface onTimeFinshListener{
        void timeFinish(int  pos);
    }
}
